package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private CommentApi commentApi;
    /*@DubboReference
    private CommentApi commentApi;*/

    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage iPage = userInfoApi.findAll(page, pagesize);
        return new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
    }

    public UserInfo findUserById(Long userId) {
        UserInfo info = userInfoApi.findById(userId);
        if(redisTemplate.hasKey(Constants.FREEZE_USER+info.getId())) {
            info.setUserStatus("2");
        }
        return info;
    }

    //查询指定用户发布的所有视频列表
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page, pagesize, uid);
    }

    //查询动态
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //1、调用API查询数据 ：Movment对象
        PageResult result = movementApi.findByUserId(uid,state,page,pagesize);
        //2、解析PageResult，获取Movment对象列表
        List<Movement> items = (List<Movement>) result.getItems();
        //3、一个Movment对象转化为一个Vo
        if(CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            if(userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                vos.add(vo);
            }
        }
        //4、构造返回值
        result.setItems(vos);
        return result;
    }

    //用户冻结
    public Map userFreeze(Map params) {
        String freezingTimeStr = (String) params.get("freezingTime");
        int freezingTime = Integer.parseInt(freezingTimeStr);
        Integer userId = (Integer) params.get("userId");
        int days = 0;
        if (freezingTime == 1) {
            days = 3;
        }
        if (freezingTime == 2) {
            days = 7;
        }
        if (freezingTime == 3) {
            days = -1;
        }
        String value = JSON.toJSONString(params);
        redisTemplate.opsForValue().set(Constants.FREEZE_USER+userId,value,days, TimeUnit.MINUTES);
        Map map = new HashMap();
        map.put("message","冻结成功");
        return map;
    }

    //用户解冻
    public Map userUnfreeze(Map params) {
        Integer userId = (Integer) params.get("userId");
        redisTemplate.delete(Constants.FREEZE_USER+userId);
        Map map = new HashMap();
        map.put("message","解冻成功");
        return map;
    }

    //分页查询评论
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        PageResult pr = commentApi.findCommentsByPage(movementId, CommentType.COMMENT,page,pagesize);
        //2、判断pr集合是否存在
        if (pr==null){
            return new PageResult();
        }
        List<Comment> items = (List<Comment>) pr.getItems();
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);

        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : items) {
            UserInfo userInfo = map.get(comment.getUserId());
            if(userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        //5、构造返回值
        pr.setItems(vos);
        return pr;
    }

    //动态详情
    public MovementsVo messagesById(String id) {
        Movement movement = movementApi.findById(id);
        Long userId = movement.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        MovementsVo init = MovementsVo.init(userInfo, movement);
        return init;
    }

    //动态通过
    public ResponseEntity pass(String[] param) {
        HashMap<String, Object> map = new HashMap<>();
        for (String pam : param) {
            Movement movement = movementApi.findById(pam);
            movement.setState(1);
            movementApi.update(pam, movement.getState());
            map.put("messages","审核通过成功");
        }
        return ResponseEntity.ok(map);
    }
    //动态驳回
    public ResponseEntity reject(String[] param) {
        HashMap<String, Object> map = new HashMap<>();
        for (String pam : param) {
            Movement movement = movementApi.findById(pam);
            movement.setState(2);
            movementApi.update(pam, movement.getState());
            map.put("messages","审核驳回成功");
        }
        return ResponseEntity.ok(map);
    }

    //置顶
    public Movement top(String id) {
        Movement movement = new Movement();
        movement.setTop(1);
        movementApi.topupdate(id,movement.getTop());
        return movement;
    }
    //取消置顶
    public Movement untop(String id) {
        Movement movement = new Movement();
        movement.setTop(0);
        movementApi.topupdate(id, movement.getTop());
        return movement;
    }

}
